package kp.rpc.fault.tolerant.impl;

import kp.rpc.fault.tolerant.TolerantStrategy;
import kp.rpc.model.RpcRequest;
import kp.rpc.model.RpcResponse;
import kp.rpc.proxy.ServiceProxyFactory;
import kp.rpc.registry.LocalRegistry;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;


@Slf4j
public class FailBackTolerantStrategy implements TolerantStrategy {
    @Override
    public RpcResponse doTolerant(Map<String, Object> context, Exception e) throws Exception {
        //todo 降级容错
        //调用本地的mock数据
        log.info("FailBackTolerantStrategy");
        RpcRequest rpcRequest = (RpcRequest) context.get("rpcRequest");
        //获取要调用的方法
        // 当前forName拿到的是公共的接口
        Class<?> implClass = Class.forName(rpcRequest.getServiceName());
        Object mockProxy = ServiceProxyFactory.getMockProxy(implClass);
        Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object invoke = method.invoke(mockProxy, rpcRequest.getArgs());
        return RpcResponse.builder().data(invoke).dataType(method.getReturnType()).message("ok").build();
    }
}
